
###
# -class TilePalette
# -usage editor.cs
# -htmldiv selectedTileset must contain name of tileset
# TilePalette manages the selection of a tile within a tileset
# in the editor
###

class TilePalette
  constructor: (@canvas) ->
    console.log(@canvas)
    @screen = @canvas.getContext('2d')
    @refreshTS()
    @offX = @offY = 0
    This = this
    setInterval(`function(){This.draw()}`,150)
    addEventListener('keydown',`function(e){This.onKeyDown(e)}`,true)
  refreshTS: () ->
    @tileset = new Tileset($("#selectedTileset").html())
    @sizeX = @tileset.sizeX
    @sizeY = @tileset.sizeY
  draw: () ->
    @screen.fillStyle = "#FFFFFF"
    @screen.fillRect(0,0,@canvas.width,@canvas.height)
    @screen.strokeStyle = "#000"
    @screen.strokeRect(64,64,64,64)
    ts = MouseFollower.prototype.TileSize*2
    W = @tileset.img.width
    H = @tileset.img.height
    @screen.drawImage(@tileset.img,@offX*ts+ts,@offY*ts+ts)
  onKeyDown: (e) ->
    ts = MouseFollower.prototype.TileSize*2
    @sizeX = @tileset.img.width/ts-1
    @sizeY = @tileset.img.height/ts-1
    if e.keyCode==87 and @offY<0
      @offY+=1 #W
    if e.keyCode==65 and @offX<0
      @offX+=1 #A
    if e.keyCode==83 and @offY>-@sizeY
      @offY-=1 #S
    if e.keyCode==68 and @offX>-@sizeX
      @offX-=1 #D